package com.jianying.day05;

import com.jianying.beans.WaterSensor;
import com.jianying.func.WaterSensorMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * ClassName: Flink04_Window_reduce
 * Package: com.atguigu.day05
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/4/3 14:24
 * @Version: 1.0
 */
public class Flink04_Window_reduce {
    public static void main(String[] args) throws Exception {
        // TODO 开滚动处理时间窗口，使用reduce对窗口中元素进行聚合
        // 取出最近10s中每个传感器采集到的水位的和
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<String> socketDS = env.socketTextStream("localhost", 8888);
        SingleOutputStreamOperator<WaterSensor> wsDS = socketDS.map(new WaterSensorMapFunction());

        // TODO 按照ID 分组
        KeyedStream<WaterSensor, String> keyByDS = wsDS.keyBy(ws -> ws.getId());

        // TODO 开窗 滚动处理时间窗口，大小10s
        WindowedStream<WaterSensor, String, TimeWindow> windowDS = keyByDS.window(
                TumblingProcessingTimeWindows.of(Time.seconds(10))
        );

        // TODO 对窗口中的数据进行聚合计算 Reduce  窗口中三个类型要一致
        SingleOutputStreamOperator<WaterSensor> reduceDS = windowDS.reduce(
                new ReduceFunction<WaterSensor>() {
                    @Override
                    public WaterSensor reduce(WaterSensor ws1, WaterSensor ws2) throws Exception {
                        System.out.println("中间累加结果：" + ws1);
                        System.out.println("新来数据：" + ws2);
                        return new WaterSensor(ws1.getId(), System.currentTimeMillis(), ws1.getVc() + ws2.getVc());
                    }
                }
        );

        // TODO 打印输出
        reduceDS.print();

        env.execute();
    }
}
